using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Game3D_dev3517b
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Model caixa;
        Video video;
        VideoPlayer player;
        KeyboardState teclado, teclado_anterior;
        DualTextureEffect efeitobasicoquadrado;
        Texture2D texturaquadrado;
        Texture2D luz;
        Model chao;
        Vector3 cameraPosition;
        Vector3 lookAt;

        Model modelo;
        BasicEffect efeitobasicoluz;
        Texture2D textura;


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        public enum Tiposefeitobasicoluz
        {
            Nenhum,
            LuzesAmbiente,
            UmaLuz,
            DuasLuzes,
            TresLuzes,
            IluminacaoPadrao,
            Especular,
            Emissiva,
            Texturizada,
            Fumaca,
        }
        Tiposefeitobasicoluz tipoAtual = Tiposefeitobasicoluz.UmaLuz;


        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            caixa = Content.Load<Model>("caixa");
            video = Content.Load<Video>("video2");
            player = new VideoPlayer();
            player.IsLooped = true;
            player.Play(video);

            efeitobasicoluz = new BasicEffect(GraphicsDevice);

            //Matriz que projeta o mundo na camera
            efeitobasicoluz.Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4,//abertura
                GraphicsDevice.Viewport.AspectRatio,//taxa de proporcao da tela
                1.0f,//plano de "perto"
                10000.0f);//plano de "longe"

            switch (tipoAtual)
            {
                case Tiposefeitobasicoluz.UmaLuz:
                    efeitobasicoluz.LightingEnabled = true;
                    efeitobasicoluz.DirectionalLight0.Enabled = true;
                    efeitobasicoluz.DirectionalLight0.DiffuseColor = Color.Blue.ToVector3();
                    efeitobasicoluz.DirectionalLight0.Direction = Vector3.Normalize(
                        new Vector3(-1,-1f,0));
                    break;
            }

            efeitobasicoquadrado = new DualTextureEffect
            (GraphicsDevice);

            chao = Content.Load<Model>("plano");
            texturaquadrado = Content.Load<Texture2D>("chao");
            luz = Content.Load<Texture2D>("mapadeluzes");


            efeitobasicoquadrado.Texture2 = luz;

            efeitobasicoquadrado.Texture = texturaquadrado;

            efeitobasicoquadrado.Projection =
                Matrix.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4,
                GraphicsDevice.Viewport.AspectRatio,
                1.0f,
                100.0f);

            efeitobasicoquadrado.View = Matrix.CreateLookAt(
                new Vector3(0, 42, 12),
                Vector3.Zero,
                Vector3.Up);

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            teclado = Keyboard.GetState();

            if (teclado.IsKeyDown(Keys.P) && !teclado_anterior.IsKeyDown(Keys.P))
            {
                if (player.State == MediaState.Playing)
                {
                    player.Pause();
                }
                else if (player.State == MediaState.Paused)
                {
                    player.Resume();
                }

            }

            if (player.Volume <= 0.9)
            {
                if (teclado.IsKeyDown(Keys.OemPlus) && !teclado_anterior.IsKeyDown(Keys.OemPlus))
                {
                    player.Volume += 0.1f;
                }
            }

            if (player.Volume >= 0.1)
            {
                if (teclado.IsKeyDown(Keys.OemMinus) && !teclado_anterior.IsKeyDown(Keys.OemMinus))
                {
                    player.Volume -= 0.1f;
                }
            }

            teclado_anterior = teclado;
            base.Update(gameTime);
        }

        private void DrawModel(Model m, Matrix world, BasicEffect be)
        {
            foreach (ModelMesh mm in m.Meshes)
            {
                foreach (ModelMeshPart mmp in mm.MeshParts)
                {
                    be.World = GetParentTransform(m, mm.ParentBone) * world;
                    GraphicsDevice.SetVertexBuffer(mmp.VertexBuffer, mmp.VertexOffset);
                    GraphicsDevice.Indices = mmp.IndexBuffer;
                    be.CurrentTechnique.Passes[0].Apply();
                    GraphicsDevice.DrawIndexedPrimitives(
                        PrimitiveType.TriangleList, 0, 0,
                        mmp.NumVertices, mmp.StartIndex, mmp.PrimitiveCount);
                }
            }
        }

        private Matrix GetParentTransform(Model m, ModelBone mb)
        {
            return (mb == m.Root) ? mb.Transform :
            mb.Transform * GetParentTransform(m, mb.Parent);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            BasicEffect effect = caixa.Meshes[0].Effects[0] as BasicEffect;

            effect.TextureEnabled = true;
            effect.Texture = player.GetTexture();

            GraphicsDevice.SamplerStates[0] =
                SamplerState.LinearClamp;

            DesenharModelo(chao, Matrix.Identity, efeitobasicoquadrado);

            switch (tipoAtual)
            {
                case Tiposefeitobasicoluz.Nenhum:
                case Tiposefeitobasicoluz.LuzesAmbiente:
                case Tiposefeitobasicoluz.UmaLuz:
                case Tiposefeitobasicoluz.DuasLuzes:
                case Tiposefeitobasicoluz.TresLuzes:
                case Tiposefeitobasicoluz.IluminacaoPadrao:
                case Tiposefeitobasicoluz.Especular:
                case Tiposefeitobasicoluz.Emissiva:
                case Tiposefeitobasicoluz.Texturizada:
                    DrawModel(caixa, Matrix.Identity, efeitobasicoluz);
                    break;
            }

            caixa.Draw(Matrix.CreateRotationX((float)gameTime.TotalGameTime.TotalSeconds)
                * Matrix.CreateScale(3f),
                 Matrix.CreateLookAt(new Vector3(5, 0, -5),
                Vector3.Zero,
                Vector3.Up),
                Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                graphics.GraphicsDevice.Viewport.AspectRatio,
                1.0f,
                100.0f));

            base.Draw(gameTime);
        }

        private void DesenharModelo(Model m, Matrix world, DualTextureEffect be)
        {
            be.World = world;
            be.CurrentTechnique.Passes[0].Apply();
            foreach (ModelMesh mm in m.Meshes)
            {
                foreach (ModelMeshPart mmp in mm.MeshParts)
                {
                    GraphicsDevice.SetVertexBuffer(mmp.VertexBuffer, mmp.VertexOffset);
                    GraphicsDevice.Indices = mmp.IndexBuffer;
                    GraphicsDevice.DrawIndexedPrimitives(
                        PrimitiveType.TriangleList, 0, 0,
                        mmp.NumVertices, mmp.StartIndex, mmp.PrimitiveCount);
                }
            }
        }
    }
}
